package it.lorenz.server.fk.business.jr;

import it.lorenz.server.fk.business.AbstractBusinessService;
import it.lorenz.server.fk.business.AbstractDTO;
import it.lorenz.server.fk.business.ex.AbstractBusinessException;
import it.lorenz.server.fk.business.ex.ValidationException;
import java.io.ByteArrayOutputStream;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import org.springframework.beans.factory.annotation.Autowired;

public class JRGeneratePDFBS extends AbstractBusinessService {

    @Autowired
    private JasperReportsManager jasperReportsManager;

    @Override
    public void doFormalValidation(AbstractDTO dto) throws ValidationException {
    }

    @Override
    public void doFunctionalValidation(AbstractDTO dto)
       throws ValidationException {
    }

    @Override
    public AbstractDTO callBusinessService(AbstractDTO param)
       throws AbstractBusinessException {
        JasperReportsDTO real = (JasperReportsDTO) param;

        JasperReport jasperReport = jasperReportsManager.loadTemplate(real.getTemplatePath());

        JasperPrint jasperPrint = jasperReportsManager.fillReport(jasperReport, real.getAttributes(), real.getDataSource());

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        jasperReportsManager.exportToPDF(jasperPrint, out);
        real.setPdfBytes(out.toByteArray());

        return real;
    }

    public void setJasperReportsManager(
       JasperReportsManager jasperReportsManager) {
        this.jasperReportsManager = jasperReportsManager;
    }
}
